package com.qgs.rabbitmqapi.dlx;

import com.qgs.rabbitmqapi.consumer.MyConsumer;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 蔡翔
 * @Date: 2019/7/19 13:26
 * @Version 1.0
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        Logger logger = LoggerFactory.getLogger(Consumer.class);

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.0.229");
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPort(5672);

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 这就是一个普通的交换机 和 队列以及路由
        String exchange = "test_dlx_exchange";
        String routingKey = "dlx.#";
        String queueName = "test_dlx_queue";

        Map<String,Object> arguments = new HashMap<>();
        //dlx.exchange这个名字可以自己取。这是一个死信交换机的名字，这个参数就是设置死信队列的关键
        //意思就是说 一旦有消息“死了” 那么久吧这个消息，重新投递到死信交换机上，再由死信交换机投递到相应的死信队列上。
        arguments.put("x-dead-letter-exchange","dlx.exchange");

        //要进行死信队列的声明
        channel.exchangeDeclare("dlx.exchange","topic",true,false,null);
        channel.queueDeclare("dlx.queue",true,false,false,null);
        //这里的# 代表 exchange上任何的消息都可以路由到queue上
        channel.queueBind("dlx.queue","dlx.exchange","#");


        //这个arguments属性，要设置到申明队列上。
        channel.queueDeclare(queueName,true,false,false,arguments);
        channel.exchangeDeclare(exchange,"topic",true);
        channel.queueBind(queueName,exchange,routingKey);



        channel.basicConsume(queueName,true,new MyConsumer(channel));
    }
}
